﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace Utility.Windows.Forms
{
    public class ListView : System.Windows.Forms.ListView
    {
        #region 构造函数
        public ListView()
        {
        }
        #endregion

        #region SetDataBinding
        public void SetDataBinding(DataTable dataTable, ArrayList columnsToShow)
        {
            try
            {
                //清空ListView
                this.Clear();

                //加载ColumnHeader
                for (int i = 0; i < columnsToShow.Count; i++)
                {
                    System.Windows.Forms.ColumnHeader columnHeader = new ColumnHeader();
                    columnHeader.Text = dataTable.Columns[columnsToShow[i].ToString()].Caption;
                    this.Columns.Add(columnHeader);
                }

                //加载数据
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    System.Windows.Forms.ListViewItem listViewItem = new ListViewItem();
                    listViewItem.SubItems[0].Text = dataTable.Rows[i][columnsToShow[0].ToString()].ToString();
                    for (int j = 1; j < columnsToShow.Count; j++)
                    {
                        listViewItem.SubItems.Add(dataTable.Rows[i][columnsToShow[j].ToString()].ToString());
                    }
                    this.Items.Add(listViewItem);
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
        #endregion
    }
}
